<?php

namespace App\Jobs;

use App\Models\Collection;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use App\Services\MakeGoldRecord\MakeGoldRecord;
use App\Services\SettleGoldRecordReselling\SettleGoldRecordReselling;
use Illuminate\Support\Str;
use Intervention\Image\Gd\Font;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class MakeBatchImageJob implements ShouldQueue
{
	use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

	public Array $images;
	public int $collectionId;

	public function __construct($images, $collectionId)
	{
		$this->images = $images;
		$this->collectionId = $collectionId;
	}

	protected function getPosterName($title)
	{
		return $title.(string)serial_uuid();
	}
	
	protected function getRemotePosterDir()
	{
		return 'images';
	}
	
	protected function getRemotePosterSavePath()
	{
		return $this->getRemotePosterDir() . '/' . $this->getPosterName();
	}
	
	protected function getLocalPosterSavePath(string $name)
	{
		$localPath = public_path('temp/ai-create-image');
		if (! File::isDirectory($localPath)) {
			File::makeDirectory($localPath, 755, true, true);
		}
		return "{$localPath}/{$name}.png";
	}

	public function handle()
	{
      /*if (Storage::exists($this->getRemotePosterSavePath())) {
			return Storage::url($this->getRemotePosterSavePath());
		}*/
		$collection = Collection::find($this->collectionId);
		$posterDir = $this->getRemotePosterDir();
		$posterName = $this->getPosterName($collection->title);
		$imgModel = Image::canvas(750, 1000, '#FFFFFF');

		foreach($this->images as $image){
			$image =  Image::make(img_path($image))->resize(750, 1000);

			$imgModel->insert($image, 'top', 0, 0);
		}

		$imgModel->save($this->getLocalPosterSavePath($posterName));

		
		// move to oss.
		Storage::putFileAs($posterDir, $this->getLocalPosterSavePath($posterName), $posterName.".png");
		
		// remove local poster.
		//File::delete($this->getLocalPosterSavePath($posterName));

		
		$collection->collectionImages()->create(['image'=>Storage::url("{$posterDir}/{$posterName}.png")]);
		//dd( Storage::url("{$posterDir}/{$posterName}"));
		
		//return Storage::url("{$posterDir}/{$posterName}");
	}

	
	
	
}
